from django.core.paginator import Paginator
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *


# Create your views here.

# 老师
class TeacherView(APIView):
    def post(self, request):
        # 提取网页提交数据
        name = request.data.get('name')
        # 判断分类是否存在
        teacher_obj = Teacher.objects.filter(name=name)
        # 如何分类，返回分类已存在
        if teacher_obj:
            return Response({"msg": "分类已存在"}, status=400)
        # 不存在时 添加

        else:
            ser = TeacherSer(data=request.data)
            # 校验数据
            if ser.is_valid():
                # 保存数据
                ser.save()
                return Response({"msg": "添加成功"}, status=200)
            else:
                return Response({"error": ser.errors})

    def get(self, request):
        tea_list = Teacher.objects.all()
        cate_ser = TeacherSer(tea_list, many=True)
        return Response(cate_ser.data)


# 登录
class LoginView(APIView):
    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')
        techer_obj = Teacher.objects.filter(name=name, password=password).first()
        if techer_obj:
            request.session['uname'] = name
            return Response({
                'status': 200,
                'msg': '登录成功',
                "data": name

            })

        return Response({
            'status': 400,
            'msg': '登录失败',
            "data": ''

        })

    def get(self, request):
        cate_list = Teacher.objects.all()
        cate_ser = TeacherSer(cate_list, many=True)
        return Response(cate_ser.data)


# 学生
class StudentView(APIView):
    def post(self, request):
        stu_name = request.data.get('stu_name')
        student_obj = Student.objects.filter(stu_name=stu_name).first()
        if student_obj:
            return Response({'msg': '学生已存在'}, status=400)
        else:
            stu_ser = StudentSer(data=request.data)
            if stu_ser.is_valid():
                stu_ser.save()
                return Response({'msg': '添加成功'}, status=200)
            else:
                return Response({"error": stu_ser.errors})

    def get(self, request):
        num = request.GET.get('num')
        Stu_list = Student.objects.all()
        paginator = Paginator(Stu_list, 3)
        page = paginator.page(num)
        Stu_ser = StudentSer(page, many=True)
        return Response({
            'data': Stu_ser.data,
            'page_list': [i for i in paginator.page_range],
            'page_sum': paginator.num_pages
        })


# 展示分页
class ShowStuView(APIView):
    # 获取分类全部数据
    def get(self, request):
        stu_list = Student.objects.all()
        stu_ser = StudentsSer(stu_list, many=True)
        return Response(stu_ser.data)
